package com.benny_driving_dri.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONUtil {

	private static JSONObject json;
	private static JSONArray jsons;

	public static JSONObject object2json(String str, List<Object> list) {

		json = new JSONObject();
		jsons = new JSONArray();
		for (Object object : list) {

			String[] attributes = getAttribute(object);
			String[] values = getFiledValues(object);

			try {
				JSONObject jo = new JSONObject();
				for (int i = 0; i < attributes.length; i++) {
					jo.put(attributes[i], values[i]);
				}
				jsons.put(jo);
				json.put(str, jsons);
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

		System.out.println(json.toString());
		return json;
	}

	private static String[] getFiledName(Object o) {
		Field[] fields = o.getClass().getDeclaredFields();
		String[] fieldNames = new String[fields.length];
		for (int i = 0; i < fields.length; i++) {
			fieldNames[i] = fields[i].getName();
		}
		return fieldNames;
	}

	private static Object getFieldValueByName(String fieldName, Object o) {
		try {
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter, new Class[] {});
			Object value = method.invoke(o, new Object[] {});
			return value;
		} catch (Exception e) {
			return null;
		}
	}

	public static String[] getFiledValues(Object o) {
		String[] fieldNames = getFiledName(o);
		Object[] value = new Object[fieldNames.length];
		String[] values = new String[fieldNames.length];
		for (int i = 0; i < fieldNames.length; i++) {
			value[i] = getFieldValueByName(fieldNames[i], o);
			values[i] = value[i] + "";
		}
		return values;
	}

	public static String[] getAttribute(Object o) {
		Field[] fields = o.getClass().getDeclaredFields();
		String[] fieldNames = new String[fields.length];
		for (int i = 0; i < fields.length; i++) {
			fieldNames[i] = fields[i].getName().toString();
		}
		return fieldNames;
	}

}
